import axios from "axios";
import { showToast } from "vant";
import { getToken, clearToken } from "@/utils/auth";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import router from "@/router";
import { useUserStore } from "@/store";

NProgress.configure({ showSpinner: false });

const StatusCodeMessage = {
  200: "服务器成功返回请求的数据",
  201: "新建或修改数据成功。",
  202: "一个请求已经进入后台排队（异步任务）",
  204: "删除数据成功",
  400: "请求错误(400)",
  401: "未授权，请重新登录(401)",
  403: "拒绝访问(403)",
  404: "请求出错(404)",
  408: "请求超时(408)",
  500: "服务器错误(500)",
  501: "服务未实现(501)",
  502: "网络错误(502)",
  503: "服务不可用(503)",
  504: "网络超时(504)"
};

const http = axios.create({
  timeout: 60 * 1000
});

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    NProgress.start(); // 进度条
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      config.headers["Authorization"] = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    const { data } = response;
    if (response.request.responseType === "blob") {
      NProgress.done();
      return { data: response };
    }
    const { message, code } = data;
    if (code !== 200) {
      NProgress.done();
      // showToast(message || "服务器端错误");
      return Promise.reject(response.data);
    }
    NProgress.done();
    return response?.data || response;
  },
  (error) => {
    NProgress.done();
    // Message.clear();
    const response = Object.assign({}, error.response);
    if (response.status === 401) {
      const userStore = useUserStore();
      if (userStore) {
        userStore.logout();
      } else {
        clearToken();
      }
      showToast("token失效，重新登录");
      router.replace("/login");
    }
    // response &&
    //   showToast(
    //     StatusCodeMessage[response.status] ||
    //       error?.response?.data?.message ||
    //       "系统异常, 请检查网络或联系管理员！"
    //   );
    return Promise.reject(error);
  }
);

const request = (config) => {
  return new Promise((resolve, reject) => {
    http
      .request(config)
      .then((res) => resolve(res.data))
      .catch((err) => reject(err));
  });
};

request.get = (url, params, headers, responseType) => {
  return request({
    method: "get",
    url,
    params,
    headers,
    responseType
  });
};

request.post = (url, params, headers, responseType) => {
  return request({
    method: "post",
    url,
    data: params,
    headers,
    responseType
  });
};

request.delete = (url, params, headers) => {
  return request({
    method: "delete",
    url,
    params,
    headers
  });
};

request.put = (url, params, headers) => {
  return request({
    method: "put",
    url,
    params,
    headers
  });
};

request.patch = (url, params, headers) => {
  return request({
    method: "patch",
    url,
    params,
    headers
  });
};

export default request;
